import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../shared/theme/app_theme.dart';
import '../../../core/providers/theme_provider.dart';
import '../../../core/providers/user_extra_info_provider.dart';
import '../../../core/providers/welcome_header_provider.dart';
import '../../../shared/utils/responsive_utils.dart';

class ProfilePage extends ConsumerWidget {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(title: const Text('我的')),
      body: ListView(
        padding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 16),
        ),
        children: <Widget>[
          const _UserInfoCard(),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
          const _UserDetailCard(),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
          const _StatsCard(),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
          _ThemeStageCard(ref: ref),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
          _AccentPaletteCard(ref: ref),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
          Container(
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceContainerHighest,
              borderRadius: BorderRadius.circular(
                ResponsiveUtils.getResponsiveRadius(context, 12),
              ),
            ),
            child: const _MenuList(),
          ),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 16)),
          Container(
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceContainerHighest,
              borderRadius: BorderRadius.circular(
                ResponsiveUtils.getResponsiveRadius(context, 12),
              ),
            ),
            child: const _SettingsList(),
          ),
        ],
      ),
    );
  }
}

class _UserInfoCard extends ConsumerWidget {
  const _UserInfoCard();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userExtraInfo = ref.watch(userExtraInfoProvider);
    final ColorScheme cs = Theme.of(context).colorScheme;

    return GestureDetector(
      onTap: () => context.go('/profile-edit'),
      child: Container(
        padding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 16),
        ),
        decoration: BoxDecoration(
          color: cs.surfaceContainerHighest,
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 12),
          ),
        ),
        child: Row(
          children: <Widget>[
            CircleAvatar(
              radius: ResponsiveUtils.getResponsiveIconSize(context, 30),
              backgroundColor: cs.primary,
              child: Icon(
                Icons.person,
                color: Colors.white,
                size: ResponsiveUtils.getResponsiveIconSize(context, 30),
              ),
            ),
            SizedBox(width: ResponsiveUtils.getResponsiveSpacing(context, 16)),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '学生用户',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(
                    height: ResponsiveUtils.getResponsiveSpacing(context, 4),
                  ),
                  Text(
                    userExtraInfo?.fullGradeInfo ?? '未设置年级',
                    style: const TextStyle(color: Colors.grey),
                  ),
                  if (userExtraInfo != null) ...[
                    SizedBox(
                      height: ResponsiveUtils.getResponsiveSpacing(context, 2),
                    ),
                    Text(
                      '目标: ${userExtraInfo.goals ?? '未设置'}',
                      style: Theme.of(
                        context,
                      ).textTheme.bodySmall?.copyWith(color: Colors.grey),
                    ),
                  ],
                ],
              ),
            ),
            Icon(Icons.chevron_right, color: cs.onSurface.withOpacity(0.5)),
          ],
        ),
      ),
    );
  }
}

class _UserDetailCard extends ConsumerWidget {
  const _UserDetailCard();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userExtraInfo = ref.watch(userExtraInfoProvider);
    final ColorScheme cs = Theme.of(context).colorScheme;

    if (userExtraInfo == null) {
      return Container(
        padding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 16),
        ),
        decoration: BoxDecoration(
          color: cs.surfaceContainerHighest,
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 12),
          ),
        ),
        child: const Center(
          child: Text('暂无用户信息', style: TextStyle(color: Colors.grey)),
        ),
      );
    }

    return GestureDetector(
      onTap: () {
        // 跳转到教材大纲页面
        context.push('/curriculum');
      },
      child: Container(
        padding: EdgeInsets.all(
          ResponsiveUtils.getResponsiveSpacing(context, 16),
        ),
        decoration: BoxDecoration(
          color: cs.surfaceContainerHighest,
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 12),
          ),
          border: Border.all(color: cs.outline.withOpacity(0.1), width: 1),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: [
                Text(
                  '学习信息',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w700,
                  ),
                ),
                const Spacer(),
                Icon(
                  Icons.chevron_right,
                  color: cs.onSurface.withOpacity(0.5),
                  size: ResponsiveUtils.getResponsiveIconSize(context, 20),
                ),
              ],
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 8)),
            Text(
              '点击查看教材大纲',
              style: TextStyle(
                fontSize: ResponsiveUtils.getResponsiveFontSize(context, 12),
                color: cs.primary,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 12)),
            _DetailItem(
              icon: Icons.school,
              label: '年级',
              value: userExtraInfo.fullGradeInfo,
            ),
            if (userExtraInfo.subjectsList.isNotEmpty) ...[
              SizedBox(
                height: ResponsiveUtils.getResponsiveSpacing(context, 8),
              ),
              _DetailItem(
                icon: Icons.book,
                label: '学习科目',
                value: userExtraInfo.subjectsList.join('、'),
              ),
            ],
            if (userExtraInfo.goals != null &&
                userExtraInfo.goals!.isNotEmpty) ...[
              SizedBox(
                height: ResponsiveUtils.getResponsiveSpacing(context, 8),
              ),
              _DetailItem(
                icon: Icons.flag,
                label: '学习目标',
                value: userExtraInfo.goals!,
              ),
            ],
          ],
        ),
      ),
    );
  }
}

class _DetailItem extends StatelessWidget {
  const _DetailItem({
    required this.icon,
    required this.label,
    required this.value,
  });

  final IconData icon;
  final String label;
  final String value;

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;

    return Row(
      children: <Widget>[
        Icon(
          icon,
          size: ResponsiveUtils.getResponsiveIconSize(context, 16),
          color: cs.primary,
        ),
        SizedBox(width: ResponsiveUtils.getResponsiveSpacing(context, 8)),
        Text(
          '$label: ',
          style: TextStyle(fontSize: 14, color: cs.onSurface.withOpacity(0.7)),
        ),
        Expanded(
          child: Text(
            value,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
          ),
        ),
      ],
    );
  }
}

class _StatsCard extends StatelessWidget {
  const _StatsCard();

  @override
  Widget build(BuildContext context) {
    final ColorScheme cs = Theme.of(context).colorScheme;
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: cs.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: const <Widget>[
          _StatItem(title: '学习天数', value: '0'),
          _StatItem(title: '完成题目', value: '0'),
          _StatItem(title: '掌握知识点', value: '0'),
        ],
      ),
    );
  }
}

class _StatItem extends StatelessWidget {
  const _StatItem({required this.title, required this.value});
  final String title;
  final String value;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text(
          value,
          style: TextStyle(
            fontSize: ResponsiveUtils.getResponsiveFontSize(context, 24),
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 4)),
        Text(title, style: const TextStyle(color: Colors.grey)),
      ],
    );
  }
}

class _MenuList extends StatelessWidget {
  const _MenuList();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _MenuTile(icon: Icons.bookmark_border, title: '错题本', onTap: () {}),
        _MenuTile(icon: Icons.refresh_outlined, title: '复习队列', onTap: () {}),
        _MenuTile(icon: Icons.analytics_outlined, title: '学习报告', onTap: () {}),
        _MenuTile(icon: Icons.settings_outlined, title: '设置', onTap: () {}),
      ],
    );
  }
}

class _MenuTile extends StatelessWidget {
  const _MenuTile({
    required this.icon,
    required this.title,
    required this.onTap,
  });
  final IconData icon;
  final String title;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Container(
        width: ResponsiveUtils.getResponsiveIconSize(context, 40),
        height: ResponsiveUtils.getResponsiveIconSize(context, 40),
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.primaryContainer,
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 10),
          ),
        ),
        child: Icon(icon, color: Theme.of(context).colorScheme.primary),
      ),
      title: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
      trailing: const Icon(Icons.chevron_right),
      onTap: onTap,
    );
  }
}

class _ThemeStageCard extends StatelessWidget {
  const _ThemeStageCard({required this.ref});
  final WidgetRef ref;

  @override
  Widget build(BuildContext context) {
    final StageTheme current = ref.watch(themeStageProvider);
    final userExtraInfo = ref.watch(userExtraInfoProvider);
    final ColorScheme cs = Theme.of(context).colorScheme;
    final Map<StageTheme, String> labels = {
      StageTheme.elementary: '小学',
      StageTheme.middle: '初中',
      StageTheme.high: '高中',
    };

    // 检查主题是否与用户年级匹配
    bool isAutoMatched = false;
    if (userExtraInfo?.grade != null) {
      final expectedTheme = _getExpectedThemeFromGrade(userExtraInfo!.grade!);
      isAutoMatched = current == expectedTheme;
    }

    return Container(
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      decoration: BoxDecoration(
        color: cs.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(
          ResponsiveUtils.getResponsiveRadius(context, 12),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Text(
                '主题风格',
                style: TextStyle(
                  fontSize: ResponsiveUtils.getResponsiveFontSize(context, 16),
                  fontWeight: FontWeight.w700,
                ),
              ),
              if (isAutoMatched) ...[
                SizedBox(
                  width: ResponsiveUtils.getResponsiveSpacing(context, 8),
                ),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: ResponsiveUtils.getResponsiveSpacing(
                      context,
                      6,
                    ),
                    vertical: ResponsiveUtils.getResponsiveSpacing(context, 2),
                  ),
                  decoration: BoxDecoration(
                    color: cs.primaryContainer,
                    borderRadius: BorderRadius.circular(
                      ResponsiveUtils.getResponsiveRadius(context, 8),
                    ),
                  ),
                  child: Text(
                    '自动',
                    style: TextStyle(
                      fontSize: ResponsiveUtils.getResponsiveFontSize(
                        context,
                        10,
                      ),
                      color: cs.onPrimaryContainer,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ],
          ),
          if (isAutoMatched) ...[
            SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 4)),
            Text(
              '根据您的年级自动设置',
              style: TextStyle(
                fontSize: ResponsiveUtils.getResponsiveFontSize(context, 12),
                color: cs.onSurface.withOpacity(0.6),
              ),
            ),
          ],
          const SizedBox(height: 12),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children:
                labels.entries.map((e) {
                  final bool selected = e.key == current;
                  return ChoiceChip(
                    label: Text(e.value),
                    selected: selected,
                    onSelected:
                        (_) => ref
                            .read(themeStageProvider.notifier)
                            .setStage(e.key),
                  );
                }).toList(),
          ),
        ],
      ),
    );
  }

  // 根据年级获取期望的主题
  StageTheme _getExpectedThemeFromGrade(String grade) {
    if (grade.contains('一年级') ||
        grade.contains('二年级') ||
        grade.contains('三年级') ||
        grade.contains('四年级') ||
        grade.contains('五年级') ||
        grade.contains('六年级')) {
      return StageTheme.elementary;
    } else if (grade.contains('初一') ||
        grade.contains('初二') ||
        grade.contains('初三')) {
      return StageTheme.middle;
    } else if (grade.contains('高一') ||
        grade.contains('高二') ||
        grade.contains('高三')) {
      return StageTheme.high;
    }
    return StageTheme.middle;
  }
}

class _SettingsList extends ConsumerWidget {
  const _SettingsList();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Column(
      children: [
        _SettingsTile(
          icon: Icons.visibility,
          title: '显示欢迎横幅',
          subtitle: '重新显示主页的欢迎信息',
          onTap: () async {
            try {
              ref.read(welcomeHeaderProvider.notifier).show();
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(const SnackBar(content: Text('欢迎横幅已重新启用')));
            } catch (e) {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text('设置失败：$e')));
            }
          },
        ),
        _SettingsTile(
          icon: Icons.visibility_off,
          title: '隐藏欢迎横幅',
          subtitle: '隐藏主页的欢迎信息',
          onTap: () async {
            try {
              ref.read(welcomeHeaderProvider.notifier).hide();
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(const SnackBar(content: Text('欢迎横幅已隐藏')));
            } catch (e) {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text('设置失败：$e')));
            }
          },
        ),
      ],
    );
  }
}

class _SettingsTile extends StatelessWidget {
  const _SettingsTile({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.onTap,
  });

  final IconData icon;
  final String title;
  final String subtitle;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Container(
        width: ResponsiveUtils.getResponsiveIconSize(context, 40),
        height: ResponsiveUtils.getResponsiveIconSize(context, 40),
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.primaryContainer,
          borderRadius: BorderRadius.circular(
            ResponsiveUtils.getResponsiveRadius(context, 10),
          ),
        ),
        child: Icon(icon, color: Theme.of(context).colorScheme.primary),
      ),
      title: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
      subtitle: Text(
        subtitle,
        style: TextStyle(
          fontSize: ResponsiveUtils.getResponsiveFontSize(context, 12),
        ),
      ),
      trailing: const Icon(Icons.chevron_right),
      onTap: onTap,
    );
  }
}

class _AccentPaletteCard extends StatelessWidget {
  const _AccentPaletteCard({required this.ref});
  final WidgetRef ref;

  @override
  Widget build(BuildContext context) {
    final AccentPalette current = ref.watch(accentPaletteProvider);
    final ColorScheme cs = Theme.of(context).colorScheme;
    final Map<AccentPalette, String> labels = {
      AccentPalette.vibrant: '鲜亮',
      AccentPalette.neon: '霓虹',
      AccentPalette.candy: '糖果',
    };
    return Container(
      padding: EdgeInsets.all(
        ResponsiveUtils.getResponsiveSpacing(context, 16),
      ),
      decoration: BoxDecoration(
        color: cs.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(
          ResponsiveUtils.getResponsiveRadius(context, 12),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '主题配色',
            style: TextStyle(
              fontSize: ResponsiveUtils.getResponsiveFontSize(context, 16),
              fontWeight: FontWeight.w700,
            ),
          ),
          SizedBox(height: ResponsiveUtils.getResponsiveSpacing(context, 12)),
          Wrap(
            spacing: ResponsiveUtils.getResponsiveSpacing(context, 8),
            runSpacing: ResponsiveUtils.getResponsiveSpacing(context, 8),
            children:
                labels.entries.map((e) {
                  final bool selected = e.key == current;
                  return ChoiceChip(
                    label: Text(e.value),
                    selected: selected,
                    onSelected:
                        (_) => ref
                            .read(accentPaletteProvider.notifier)
                            .setPalette(e.key),
                  );
                }).toList(),
          ),
        ],
      ),
    );
  }
}
